package cn.edu.scau.cmi.ema.service;

import java.util.List;
import java.util.Set;

import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Transactional;


import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.hibernate.Session;
import cn.edu.scau.cmi.ema.dao.*;
import cn.edu.scau.cmi.ema.domain.*;
import cn.edu.scau.cmi.ema.util.CmiSqlUtil;
import cn.edu.scau.cmi.ema.domain.base.CmiPagination;
import cn.edu.scau.cmi.ema.service.base.CmiEmaService;

import java.io.IOException;
import java.util.Map;
import java.util.HashMap;
import java.util.Set;
import java.util.HashSet;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import javax.persistence.Query;
import java.util.Iterator;
@Service("DetectmethodService")
@Transactional

public class DetectmethodServiceImpl extends CmiEmaService implements DetectmethodService {
	public DetectmethodServiceImpl() {
	}

	@Transactional
	public Detectmethod saveDetectmethod(Detectmethod detectmethod) {
		Set<Detectdetail> existingDetectdetailsForDetectmethod = new HashSet<Detectdetail>();
		Set<Feature> existingFeaturesForDetectmethod = new HashSet<Feature>();
		Set<Foodbatch> existingFoodbatchsForDetectmethod = new HashSet<Foodbatch>();

		Set<Detectdetail> selectedDetectdetailsForDetectmethod = detectmethod.getDetectdetailsForDetectmethod();
		Set<Feature> selectedFeaturesForDetectmethod = detectmethod.getFeaturesForDetectmethod();
		Set<Foodbatch> selectedFoodbatchsForDetectmethod = detectmethod.getFoodbatchsForDetectmethod();

		if (detectmethod.getId() == null) {

			Detectmethod existingDetectmethod = detectmethodDAO
					.findDetectmethodByPhysicalPrimaryKey(detectmethod.getName());

			if (isEquals(detectmethod, existingDetectmethod)) {
				return existingDetectmethod;
			}

			detectmethod = detectmethodDAO.store(detectmethod);
			detectmethodDAO.flush();

			for (Detectdetail relatedDetectdetail : selectedDetectdetailsForDetectmethod) {
				relatedDetectdetail.setDetectmethod(detectmethod);
				detectdetailDAO.store(relatedDetectdetail);
			}
			for (Feature relatedFeature : selectedFeaturesForDetectmethod) {
				relatedFeature.setDetectmethod(detectmethod);
				featureDAO.store(relatedFeature);
			}
			for (Foodbatch relatedFoodbatch : selectedFoodbatchsForDetectmethod) {
				relatedFoodbatch.setDetectmethod(detectmethod);
				foodbatchDAO.store(relatedFoodbatch);
			}
		} else {
			Detectmethod existingDetectmethod = detectmethodDAO.findDetectmethodByPrimaryKey(detectmethod.getId());

			existingDetectdetailsForDetectmethod = existingDetectmethod.getDetectdetailsForDetectmethod();
			existingFeaturesForDetectmethod = existingDetectmethod.getFeaturesForDetectmethod();
			existingFoodbatchsForDetectmethod = existingDetectmethod.getFoodbatchsForDetectmethod();

			Set<Detectdetail> prepareDeleteDetectdetailsForDetectmethod = new HashSet<Detectdetail>();
			Set<Detectdetail> prepareAddDetectdetailsForDetectmethod = new HashSet<Detectdetail>();

			prepareDeleteDetectdetailsForDetectmethod.addAll(selectedDetectdetailsForDetectmethod);
			prepareDeleteDetectdetailsForDetectmethod.addAll(existingDetectdetailsForDetectmethod);

			prepareAddDetectdetailsForDetectmethod.addAll(selectedDetectdetailsForDetectmethod);
			prepareAddDetectdetailsForDetectmethod.addAll(existingDetectdetailsForDetectmethod);

			prepareDeleteDetectdetailsForDetectmethod.removeAll(selectedDetectdetailsForDetectmethod);
			prepareAddDetectdetailsForDetectmethod.removeAll(existingDetectdetailsForDetectmethod);

			for (Detectdetail relatedDetectdetail : prepareAddDetectdetailsForDetectmethod) {
				relatedDetectdetail.setDetectmethod(detectmethod);
				detectdetailDAO.store(relatedDetectdetail);
			}

			for (Detectdetail relatedDetectdetail : prepareDeleteDetectdetailsForDetectmethod) {
				relatedDetectdetail.setDetectmethod(null);
				detectdetailDAO.store(relatedDetectdetail);
			}
			Set<Feature> prepareDeleteFeaturesForDetectmethod = new HashSet<Feature>();
			Set<Feature> prepareAddFeaturesForDetectmethod = new HashSet<Feature>();

			prepareDeleteFeaturesForDetectmethod.addAll(selectedFeaturesForDetectmethod);
			prepareDeleteFeaturesForDetectmethod.addAll(existingFeaturesForDetectmethod);

			prepareAddFeaturesForDetectmethod.addAll(selectedFeaturesForDetectmethod);
			prepareAddFeaturesForDetectmethod.addAll(existingFeaturesForDetectmethod);

			prepareDeleteFeaturesForDetectmethod.removeAll(selectedFeaturesForDetectmethod);
			prepareAddFeaturesForDetectmethod.removeAll(existingFeaturesForDetectmethod);

			for (Feature relatedFeature : prepareAddFeaturesForDetectmethod) {
				relatedFeature.setDetectmethod(detectmethod);
				featureDAO.store(relatedFeature);
			}

			for (Feature relatedFeature : prepareDeleteFeaturesForDetectmethod) {
				relatedFeature.setDetectmethod(null);
				featureDAO.store(relatedFeature);
			}
			Set<Foodbatch> prepareDeleteFoodbatchsForDetectmethod = new HashSet<Foodbatch>();
			Set<Foodbatch> prepareAddFoodbatchsForDetectmethod = new HashSet<Foodbatch>();

			prepareDeleteFoodbatchsForDetectmethod.addAll(selectedFoodbatchsForDetectmethod);
			prepareDeleteFoodbatchsForDetectmethod.addAll(existingFoodbatchsForDetectmethod);

			prepareAddFoodbatchsForDetectmethod.addAll(selectedFoodbatchsForDetectmethod);
			prepareAddFoodbatchsForDetectmethod.addAll(existingFoodbatchsForDetectmethod);

			prepareDeleteFoodbatchsForDetectmethod.removeAll(selectedFoodbatchsForDetectmethod);
			prepareAddFoodbatchsForDetectmethod.removeAll(existingFoodbatchsForDetectmethod);

			for (Foodbatch relatedFoodbatch : prepareAddFoodbatchsForDetectmethod) {
				relatedFoodbatch.setDetectmethod(detectmethod);
				foodbatchDAO.store(relatedFoodbatch);
			}

			for (Foodbatch relatedFoodbatch : prepareDeleteFoodbatchsForDetectmethod) {
				relatedFoodbatch.setDetectmethod(null);
				foodbatchDAO.store(relatedFoodbatch);
			}
			detectmethod = detectmethodDAO.store(detectmethod);
			detectmethodDAO.flush();
		}

		detectdetailDAO.flush();
		featureDAO.flush();
		foodbatchDAO.flush();
		return detectmethod;
	}

	public void deleteDetectmethod(Detectmethod detectmethod) {
		detectmethodDAO.remove(detectmethod);
		detectmethodDAO.flush();
	}

	@Transactional
	public void deleteDetectmethods(Set<Integer> deleteDetectmethodsId) {
		Query query = detectmethodDAO.createNamedQuery("deleteDetectmethodsById", -1, -1);
		query.setParameter(1, deleteDetectmethodsId);
		query.executeUpdate();
	}

	@Transactional
	public Set<Detectmethod> loadDetectmethods() {
		return detectmethodDAO.findAllDetectmethods();

	}

	@Transactional
	public Set<Detectmethod> loadReferenceDetectmethods(Set<Detectmethod> detectmethods) {
		Iterator<Detectmethod> detectmethodsIterator = detectmethods.iterator();
		Set<Detectmethod> referencedDetectmethods = new HashSet<>();
		while (detectmethodsIterator.hasNext()) {
			Detectmethod currentDetectmethod = detectmethodsIterator.next();

			if (!currentDetectmethod.getDetectdetailsForDetectmethod().isEmpty()) {
				referencedDetectmethods.add(currentDetectmethod);
				continue;
			}

			if (!currentDetectmethod.getFeaturesForDetectmethod().isEmpty()) {
				referencedDetectmethods.add(currentDetectmethod);
				continue;
			}

			if (!currentDetectmethod.getFoodbatchsForDetectmethod().isEmpty()) {
				referencedDetectmethods.add(currentDetectmethod);
				continue;
			}
		}
		return referencedDetectmethods;
	}

	public Set<Detectmethod> loadDetectmethodsByIdSet(Set<Integer> detectmethodIdSet) {

		Iterator<Integer> detectmethodIdIterator = detectmethodIdSet.iterator();
		Set<Detectmethod> detectmethodSet = new HashSet<>();
		while (detectmethodIdIterator.hasNext()) {
			Integer id = detectmethodIdIterator.next();
			Detectmethod currentDetectmethod = detectmethodDAO.findDetectmethodById(id);
			detectmethodSet.add(currentDetectmethod);
		}
		return detectmethodSet;
	}

	@Transactional
	public List<Detectmethod> findAllDetectmethods(Integer startResult, Integer maxRows) {
		return new java.util.ArrayList<Detectmethod>(detectmethodDAO.findAllDetectmethods(startResult, maxRows));
	}

	@Transactional
	public Detectmethod findDetectmethodByPrimaryKey(Integer id) {
		return detectmethodDAO.findDetectmethodByPrimaryKey(id);
	}

	@Transactional
	public Integer countDetectmethods() {
		return ((Long) detectmethodDAO.createQuerySingleResult("select count(o) from Detectmethod o").getSingleResult())
				.intValue();
	}

	@Transactional
	public Integer countDetectmethods(CmiPagination page) {
		String sql = CmiSqlUtil.createCountHql(page, Detectmethod.class);
		return ((Long) detectmethodDAO.createQuerySingleResult(sql).getSingleResult()).intValue();
	}

	/**
	 * search for name with ajax
	 * 
	 */
	@Transactional
	public Integer countDetectmethodsByName(String queryName) {
		Query query = detectmethodDAO.createNamedQuery("countDetectmethodsByName", -1, -1);
		query.setParameter(1, queryName);
		return new Long((long) query.getSingleResult()).intValue();
	}

	@Transactional
	public Integer countDetectmethodsByDetachedCriteria(CmiPagination page) {
		DetachedCriteria detachedCriteria = CmiSqlUtil.createDetachedCriteria(page, Detectmethod.class);
		Session session = entityManager.unwrap(Session.class);
		detachedCriteria.setProjection(Projections.rowCount());
		return new Long((long) detachedCriteria.getExecutableCriteria(session).uniqueResult()).intValue();
	}

	public Map<String, ?> loadDetectmethodObjectReferencedSet(Detectmethod detectmethod) {
		HashMap<String, Object> objectReferencedSetMap = new HashMap<>();

		Set<Integer> detectdetailsIds = new HashSet<Integer>();
		for (Detectdetail obj : detectmethod.getDetectdetailsForDetectmethod()) {

			detectdetailsIds.add(obj.getId());
		}
		objectReferencedSetMap.put("detectdetailsIds", detectdetailsIds);
		Set<Integer> featuresIds = new HashSet<Integer>();
		for (Feature obj : detectmethod.getFeaturesForDetectmethod()) {

			featuresIds.add(obj.getId());
		}
		objectReferencedSetMap.put("featuresIds", featuresIds);
		Set<Integer> foodbatchsIds = new HashSet<Integer>();
		for (Foodbatch obj : detectmethod.getFoodbatchsForDetectmethod()) {

			foodbatchsIds.add(obj.getId());
		}
		objectReferencedSetMap.put("foodbatchsIds", foodbatchsIds);

		return objectReferencedSetMap;
	}

	public Map<String, ?> loadDetectmethodClassReferencedSet(Detectmethod detectmethod) {
		HashMap<String, Object> classReferencedSetMap = new HashMap<>();
		classReferencedSetMap.put("detectdetails", detectdetailDAO.findAllDetectdetails());
		classReferencedSetMap.put("features", featureDAO.findAllFeatures());
		classReferencedSetMap.put("foodbatchs", foodbatchDAO.findAllFoodbatchs());

		return classReferencedSetMap;
	}

	public boolean isEquals(Detectmethod detectmethod, Object obj) {
		if (obj == detectmethod)
			return true;
		if (!(obj instanceof Detectmethod))
			return false;
		Detectmethod comparedDetectmethod = (Detectmethod) obj;
		if (!CheckPropertyEqual(detectmethod.getName(), comparedDetectmethod.getName())) {
			return false;
		}
		return true;
	}

	public static <T> boolean CheckPropertyEqual(T originProperty, T comparedProperty) {
		// 基本类型经过参数传递后会自动装箱
		String[] className = originProperty.getClass().getName().split("\\.");
		if (className[0].equals("java") && className[1].equals("math")) {
			return ((Comparable) originProperty).compareTo(comparedProperty) == 0 ? true : false;
		} else {
			return originProperty.equals(comparedProperty);
		}
	}
}

